/*
 * CustomerBean.java
 *
 * Created on 27 March 2007, 12:20
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package usyd.comp5348;

import java.lang.reflect.Method;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceException;
import javax.persistence.Query;
import usyd.comp5348.Customer;

/**
 *
 * @author Yuezhong Zhang
 */
@Stateless(mappedName="ejb/Customer")
public class CustomerBean implements CustomerRemote, CustomerLocal {
    
    @PersistenceContext
    private EntityManager em;
           
    /** Creates a new instance of CustomerBean */
    public CustomerBean() {
        
    }
    
    /**
     * Create a customer,
     *@return  customer's id
     */
    public int createCustomer(CustomerInfo customer) throws CustomerException {
        try {
            Customer c = new Customer(customer);
            em.persist(c);
            customer.setId(c.getId());
            return customer.getId();
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomerException("Could not store new Customer", e);
        }
    }
    
    public CustomerInfo getCustomerById(int id) throws CustomerException{
        try {
            Customer c = em.find(Customer.class, id);
            if (c==null)
                return null;
            return c.getCustomerInfo();
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomerException("Could not retrieve Customer by Id", e);
        }
    }
    
    
    public void deleteCustomer(int id) throws CustomerException{
        Customer c = null;
        try {
            c = em.find(Customer.class, id);
            em.remove(c);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomerException("Could not remove Customer by Id", e);
        }
        if (c==null)
            throw new CustomerException("Could not remove customer(" + id + ") - does not exist");
    }
    
    public void modifyCustomer(CustomerInfo customer) throws CustomerException{
        try {
            Customer c = new Customer(customer);
            em.merge(c);
            customer.setId(c.getId());
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomerException("Could not modify existing Customer", e);
        }
    }
}
